const imgViewContainer = document.getElementById('image-view-container');
const imgs = document.getElementsByClassName('img');
let slickImgs;  // 在初始化图片浏览列表后生成
const slickBoxBk = document.getElementById('image-view-slick-box-bk');
const imgViewIndex = document.getElementById('image-view-index');
const imgViewSlickList = document.getElementById('image-view-slick-list');
const btnImgViewMirror = document.getElementById('image-view-btn-mirror');
const btnImgViewRotL = document.getElementById('image-view-btn-rotL');
const btnImgViewRotR = document.getElementById('image-view-btn-rotR');
const btnImgViewFullScreen = document.getElementById('image-view-btn-fullscreen');
const btnImgViewPlay = document.getElementById('image-view-btn-play');
const btnImgViewStop = document.getElementById('image-view-btn-stop');
const btnImgViewShare = document.getElementById('image-view-btn-share');
const btnImgViewClose = document.getElementById('image-view-btn-close');
const btnImgViewLeft = document.getElementById('image-view-btn-left');
const btnImgViewRight = document.getElementById('image-view-btn-right');

// 当前显示的图片序号
let currentImgViewSeq = -1;
let enableMouseAndTouchEvent = true;
const lazyImgs = document.getElementsByClassName('img-lazy');

// 设置css变量值
function setCssVar(name, value) {
    document.documentElement.style.setProperty(name, value);
}
// 页面宽度
function clientWidth() {
    return document.documentElement.clientWidth;
}
// 页面高度
function clientHeight() {
    return document.documentElement.clientHeight;
}
// 设置图片浏览列表移动距离
function setSlickListTranslateX(x) {
    imgViewSlickList.style.transform = `translateX(${x}px)`;
}
// 设置图片浏览列表移动偏移距离
function offsetSlickListTranslateX(ox) {
    let lastX = parseInt(imgViewSlickList.style.transform.match(/[\d-]+/)[0]);
    setSlickListTranslateX(lastX + ox);
}
// 移除移动动画
function removeListMoveAnimation() {
    imgViewSlickList.style.transition = 'unset';
}
// 设置移动动画，默认时长0.3s
function setListMoveAnimation(t) {
    t = t ? t : 0.3;
    imgViewSlickList.style.transition = `all ${t}s ease`;
    setTimeout(() => {
        removeListMoveAnimation();
    }, t * 1000);
}
function updateSlickBoxBk(url) {
    if (isFullScreen()) {
        slickBoxBk.style.backgroundImage = `url(${url})`;
    } else {
        slickBoxBk.style.backgroundImage = '';
    }
}
// 显示某个序号的图片
function showImageView(idx) {
    setSlickListTranslateX(-1 * clientWidth() * idx);
    const curImgView = slickImgs[idx];
    curImgView.style.opacity = '1';
    curImgView.src = curImgView.dataset.src;
    if (curImgView.src.indexOf('act=pre') != -1) {
        let loadImg = new Image();
        loadImg.src = curImgView.src.split('?')[0];
        loadImg.onload = () => {
            curImgView.src = loadImg.src;
            updateSlickBoxBk(curImgView.src);
            loadImg = null;
        }
    } else {
        updateSlickBoxBk(curImgView.src);
    }
    imgViewContainer.style.display = 'unset';
    imgViewIndex.innerText = `${idx + 1}/${slickImgs.length}`
}
let slideTimer;
function handlePlay() {
    if (slideTimer) return;
    slideTimer = setInterval(showNextItem, 2000);
    Toast.info('开始播放幻灯片', imgViewContainer);
    btnImgViewPlay.style.display = 'none';
    btnImgViewStop.style.display = 'unset';
}
function handleStop(e, _) {
    if (!slideTimer) return;
    clearInterval(slideTimer);
    slideTimer = null;
    if (_ || !isFullScreen()) {
        Toast.info('停止播放幻灯片');
    } else if (isFullScreen()){
        Toast.info('停止播放幻灯片', imgViewContainer);
    }
    btnImgViewPlay.style.display = 'unset';
    btnImgViewStop.style.display = 'none';
}
// 关闭图片浏览
function handleClose() {
    exitFullScreen();
    fadeout(imgViewContainer);
    currentImgViewSeq = -1;
    handleStop(1, 1);
}
// 显示下一张图片
function showNextItem() {
    translucent(slickImgs[currentImgViewSeq]);
    if (currentImgViewSeq != imgs.length - 1) {
        setListMoveAnimation();
    }
    currentImgViewSeq = (currentImgViewSeq + 1) % imgs.length;
    untranslucent(slickImgs[currentImgViewSeq]);
    showImageView(currentImgViewSeq);
}
// 显示上一张图片
function showPrevItem() {
    translucent(slickImgs[currentImgViewSeq]);
    if (currentImgViewSeq != 0) {
        setListMoveAnimation();
    }
    currentImgViewSeq = (currentImgViewSeq - 1 + imgs.length) % imgs.length;
    untranslucent(slickImgs[currentImgViewSeq]);
    showImageView(currentImgViewSeq);
}
// 将图片添加到浏览列表中
function addListImg(dataSrc, src) {
    let slickItem = document.createElement('div');
    slickItem.className = 'image-view-slick-item';
    slickItem.innerHTML = `<div class="image-view-slick-item-bk"></div><div class="image-view-slick-item-inner"><img class="image-view-slick-img" data-src="${dataSrc}" src="${src}"></div>`
    imgViewSlickList.appendChild(slickItem);
}
// 初始化图片浏览列表
function initSlickList() {
    for (let i = 0; i < imgs.length; i++) {
        const e = imgs[i];
        addListImg(e.dataset.src, e.src);
        e.onclick = () => {
            currentImgViewSeq = i;
            fadein(imgViewContainer);
            showImageView(currentImgViewSeq);
        }
    }
    slickImgs = document.getElementsByClassName('image-view-slick-img');
}
function handleShare() {
    const clip = setClipboardText(location.href.split('#')[0] + `#imgs%5B${currentImgViewSeq}%5D`);
    if (clip.res) {
        Toast.info('已复制图片分享链接', imgViewContainer);
    } else {
        Toast.error(`图片分享链接复制失败：${clip.msg}`, imgViewContainer);
    }
}
function handleFullScreen() {
    if (isFullScreen()) {
        exitFullScreen();
        slickBoxBk.style.backgroundImage = '';
    } else {
        showFullScreen(imgViewContainer);
        slickBoxBk.style.backgroundImage = `url(${slickImgs[currentImgViewSeq].src})`;
    }
}
function getCurrentRotateDeg() {
    let style = slickImgs[currentImgViewSeq].style.transform;
    try {
        let deg = parseInt(style.match(/rotate\(-?\d+deg\)/)[0].match(/-?\d+/)[0]);
        return deg;
    } catch (e) {
        return 0;
    }
}
function getCurrentMirrorDeg() {
    let style = slickImgs[currentImgViewSeq].style.transform;
    try {
        let deg = parseInt(style.match(/rotateY\(-?\d+deg\)/)[0].match(/-?\d+/)[0]);
        return deg;
    } catch (e) {
        return 0;
    }
}
function rotateImage(deg) {
    if (deg === 0 || deg % 180 === 0) {
        slickImgs[currentImgViewSeq].style.width = '90%';
        slickImgs[currentImgViewSeq].style.height = '90%';
    } else {
        slickImgs[currentImgViewSeq].style.width = 'calc(0.9*var(--winH))';
        slickImgs[currentImgViewSeq].style.height = 'calc(0.9*var(--winW))';
    }
    const pat = /rotate\(-?\d+deg\)/;
    let style = slickImgs[currentImgViewSeq].style.transform;
    if (!style.match(pat)) {
        style += ` rotate(${deg}deg)`;
    } else {
        style = style.replace(pat, `rotate(${deg}deg)`);
    }
    slickImgs[currentImgViewSeq].style.transform = style;
}
function mirrorImage(m) {
    m = m ? true : false;
    let deg = 0;
    if (m) {
        deg = 180;
    }
    const pat = /rotateY\(-?\d+deg\)/;
    let style = slickImgs[currentImgViewSeq].style.transform;
    if (!style.match(pat)) {
        style += ` rotateY(${deg}deg)`;
    } else {
        style = style.replace(pat, `rotateY(${deg}deg)`);
    }
    slickImgs[currentImgViewSeq].style.transform = style;
}
// 镜像（水平）
function handleMirror() {
    let deg = getCurrentMirrorDeg();
    mirrorImage((deg == 0) ? true : false);
}
function handleRotateLeft() {
    let deg = getCurrentRotateDeg() - 90;
    rotateImage(deg);
}
function handleRotateRight() {
    let deg = getCurrentRotateDeg() + 90;
    rotateImage(deg);
}
// 解析网址中的图片播放
function parseUrlImageView(url) {
    let ul = url.split('#');
    if (!ul) return;
    let selector = decodeURI(ul[ul.length - 1]);
    if (!selector) return;
    let pat = /imgs\[\d+\]/;
    if (!pat.test(selector)) return;
    let idx = parseInt(selector.match(/\d+/)[0]);
    if (idx < 0 || idx >= imgs.length) return;
    currentImgViewSeq = idx;
    showImageView(currentImgViewSeq);
}
// 鼠标和触摸事件处理器
function MouseAndTouchEventHandler() {
    let isPressed = false; // 鼠标是否按下
    let oldX = 0, newX = 0, downX = 0;
    this.handleStart = (mx) => {
        if (!enableMouseAndTouchEvent) return;
        isPressed = true;
        newX = oldX = downX = parseInt(mx);
    };
    this.handleEnd = () => {
        if (!enableMouseAndTouchEvent) return;
        if (!isPressed) {
            return;
        }
        isPressed = false;
        let moveX = newX - downX;
        if (moveX > clientWidth() / 4) {
            showPrevItem();
            oldX = newX = downX = 0;
        } else if (moveX < -1 * clientWidth() / 4) {
            showNextItem();
            oldX = newX = downX = 0;
        } else {
            offsetSlickListTranslateX(-1 * moveX);
            setListMoveAnimation();
        }
    };
    this.handleMove = (mx) => {
        if (!enableMouseAndTouchEvent) return;
        if (!isPressed) {
            return;
        }
        newX = parseInt(mx);
        let offsetX = newX - oldX;
        oldX = newX;
        offsetSlickListTranslateX(offsetX);
    };
    this.handleAbort = () => {
        if (!enableMouseAndTouchEvent) return;
        if (!isPressed) {
            return;
        }
        isPressed = false;
        offsetSlickListTranslateX(downX - newX);
        setListMoveAnimation();
    }
}
// 初始化图片浏览列表的鼠标事件
function initSlickMouseEvent() {
    const hMouse = new MouseAndTouchEventHandler();
    imgViewSlickList.onmousedown = (e) => {
        hMouse.handleStart(e.clientX);
    }
    imgViewSlickList.onmouseup = (e) => {
        hMouse.handleEnd();
    }
    imgViewSlickList.onmousemove = (e) => {
        hMouse.handleMove(e.clientX);
    }
    imgViewSlickList.onmouseout = (e) => {
        hMouse.handleAbort();
    }
}
// 初始化图片浏览列表的触摸事件
function initSlickTouchEvent() {
    const hTouch = new MouseAndTouchEventHandler();
    imgViewSlickList.addEventListener('touchstart', (e) => {
        hTouch.handleStart(e.touches[0].clientX);
    }, { passive: true });
    imgViewSlickList.addEventListener('touchend', (e) => {
        hTouch.handleEnd();
    });
    imgViewSlickList.addEventListener('touchmove', (e) => {
        hTouch.handleMove(e.touches[0].clientX);
    }, { passive: true });
    imgViewSlickList.addEventListener('touchcancel', (e) => {
        hTouch.handleAbort();
    });
}
// 图片懒加载器
function ImageLazyLoader() {
    let _name = 'data-src';
    let ob = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (!entry.isIntersecting) {
                return;
            }
            let target = entry.target;
            let loadImg = new Image();
            loadImg.src = target.getAttribute(_name);
            loadImg.onload = (e) => {
                target.src = loadImg.src;
                loadImg = undefined;
                ob.unobserve(target);
            }
        });
    }, {
        root: null,
        threshold: 0
    });
    this.bind = (elements, realSrcPropertyName) => {
        _name = realSrcPropertyName;
        if (!isIterable(elements)) {
            elements = [elements];
        }
        for (let i = 0; i < elements.length; i++) {
            ob.observe(elements[i]);
        }
    };
}
// 处理视口尺寸变化
function handelSizeChanged() {
    let winW = clientWidth();
    let winH = clientHeight();
    let boxW = winW * imgs.length;
    setSlickListTranslateX(-1 * winW * currentImgViewSeq);
    setCssVar('--boxW', `${boxW}px`);
    setCssVar('--winW', `${winW}px`);
    setCssVar('--winH', `${winH}px`);
}
btnImgViewClose.onclick = handleClose;
btnImgViewLeft.onclick = showPrevItem;
btnImgViewRight.onclick = showNextItem;
btnImgViewPlay.onclick = handlePlay;
btnImgViewStop.onclick = handleStop;
btnImgViewShare.onclick = handleShare;
btnImgViewFullScreen.onclick = handleFullScreen;
btnImgViewRotL.onclick = handleRotateLeft;
btnImgViewRotR.onclick = handleRotateRight;
btnImgViewMirror.onclick = handleMirror;
document.onkeydown = (e) => {
    if (currentImgViewSeq == -1) return;
    let kc = e.keyCode;
    if (kc == 37) {
        if (e.ctrlKey) btnImgViewRotL.click();
        else btnImgViewLeft.click(); 
    } else if (kc == 39) {
        if (e.ctrlKey) btnImgViewRotR.click();
        else btnImgViewRight.click();
    } else if (kc == 32) {
        if (e.ctrlKey) btnImgViewMirror.click();
    } else if (kc == 27) {
        btnImgViewClose.click();
    }
}
window.onresize = handelSizeChanged;
window.onhashchange = (e) => {
    parseUrlImageView(e.newURL);
}
pushWindowOnload(() => {
    initSlickList();
    handelSizeChanged();
    parseUrlImageView(document.URL);
    initSlickMouseEvent();
    initSlickTouchEvent();
    let ob = new ImageLazyLoader();
    ob.bind(lazyImgs, 'data-src');
});
